package com.qf.smsplatform.search.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatform.common.enums.InterfaceExceptionEnums;
import com.qf.smsplatform.common.exception.SmsException;
import com.qf.smsplatform.common.model.StandardReport;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.search.service.ElasticsearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class ElasticsearchServiceImpl implements ElasticsearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Value("${log-index}")
    private String index;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void saveLog(StandardSubmit submit) throws IOException {
        //1. 获取索引名称
        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());

        //2. request
        IndexRequest request = new IndexRequest();
        request.index(indexName);
        request.id(submit.getSequenceId());  //  为null，说明是策略模块发送的消息，不为null，说明是网关模块发送的消息

        //3. 封装
        request.source(objectMapper.writeValueAsString(submit), XContentType.JSON);
        //4. 执行并获取结果
        IndexResponse resp = restHighLevelClient.index(request, RequestOptions.DEFAULT);

        //5. 根据结果判断执行是否成功
        if(!resp.getResult().toString().equalsIgnoreCase("created")){
            log.error("【搜索模块】添加日志 ， 添加日志失败！！ result = {},submit = {}",resp.getResult().toString(),submit);
            throw new SmsException(InterfaceExceptionEnums.SEARCH_SAVE_LOG_ERROR);
        }
    }

    @Override
    public void updateLog(StandardReport report) throws IOException {
        //1. 获取索引名称
        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());

        //2. request
        UpdateRequest request = new UpdateRequest();
        request.index(indexName);
        request.id(report.getSequenceId());

        //3. 封装
        Map<String, Object> source = new HashMap<>();
        source.put("reportState",report.getState());
        source.put("errorCode",report.getErrorCode());
        request.doc(source);

        //4. 执行并获取结果
        UpdateResponse resp = restHighLevelClient.update(request, RequestOptions.DEFAULT);

        //5. 根据结果判断执行是否成功  updated
        String result = resp.getResult().toString();
        if(!result.equalsIgnoreCase("updated")){
            log.error("【搜索模块】修改日志 ， 修改日志失败！！ result = {},report = {}",result,report);
            throw new SmsException(InterfaceExceptionEnums.SEARCH_UPDATE_LOG_ERROR);
        }
    }

    @Override
    public Long searchLogCount(Map parameter) throws IOException {
        SearchResponse resp = getSearchResponse(parameter);
        //5. 返回数据条数
        long count = resp.getHits().getTotalHits().value;
        return count;
    }

    @Override
    public List<Map> searchLog(Map parameter) throws IOException {
        //1. 调用之前封装好的方法，获取resp
        SearchResponse resp = getSearchResponse(parameter);
        //2. 封装数据
        List<Map> data = new ArrayList<>();
        for (SearchHit hit : resp.getHits().getHits()) {
            Map<String, Object> source = hit.getSourceAsMap();
            // 高亮显示的数据
            HighlightField messageContentField = hit.getHighlightFields().get("messageContent");
            if(messageContentField != null){
                String messageContent = messageContentField.fragments()[0].string();
                source.put("messageContent",messageContent);
            }
            data.add(source);
        }
        return data;
    }

    @Override
    public Map<String, Long> statSendStatus(Map parameter) throws IOException {
        //1. 获取索引名称    TODO 根据parameter中的startTime和endTime判断查询的哪些索引
        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());

        //2. request
        SearchRequest request = new SearchRequest();
        request.indices(indexName);

        //3. 封装
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //3.1 设置聚合函数
        sourceBuilder.aggregation(AggregationBuilders.histogram("agg").field("reportState").interval(1));

        //3.2 设置查询条件
        // clientID客户id,keyword关键字,mobile手机号,startTime开始时间,endTime结束时间
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // clientID客户id
        Integer clientID = (Integer) parameter.get("clientID");
        if(clientID != null){
            boolQuery.must(QueryBuilders.termQuery("clientID",clientID));
        }
        // startTime开始时间,endTime结束时间
        Long startTime = (Long) parameter.get("startTime");
        Long endTime = (Long) parameter.get("endTime");
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if(startTime != null){
            rangeQuery.gte(startTime);
        }
        if(endTime != null){
            rangeQuery.lte(endTime);
        }
        boolQuery.must(rangeQuery);
        sourceBuilder.query(boolQuery);
        // 将sourceBuilder设置给request
        request.source(sourceBuilder);

        //4. 执行并获取返回结果
        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = resp.getAggregations();
        Histogram agg = aggregations.get("agg");
        List<? extends Histogram.Bucket> buckets = agg.getBuckets();
        //5. 封装数据
        Map<String, Long> data = new HashMap<>();
        for (Histogram.Bucket bucket : buckets) {
            Double key = (Double) bucket.getKey();
            if(key == 0.0){   // 代表成功
                data.put("0",bucket.getDocCount());
            }else if(key == 1.0){
                data.put("1",bucket.getDocCount());
            }else{
                data.put("2",bucket.getDocCount());
            }
        }
        //6. 返回
        return data;
    }

    private SearchResponse getSearchResponse(Map parameter) throws IOException {
        //1. 获取索引名称    TODO 根据parameter中的startTime和endTime判断查询的哪些索引
        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());

        //2. request
        SearchRequest request = new SearchRequest();
        request.indices(indexName);

        //3. 封装参数
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //3.1 设置查询数据的条件
        // clientID客户id,keyword关键字,mobile手机号,startTime开始时间,endTime结束时间
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // clientID客户id
        Integer clientID = (Integer) parameter.get("clientID");
        if(clientID != null){
            boolQuery.must(QueryBuilders.termQuery("clientID",clientID));
        }
        // keyword关键字
        String keyword = (String) parameter.get("keyword");
        if(!StringUtils.isEmpty(keyword)){
            boolQuery.must(QueryBuilders.matchQuery("messageContent",keyword));
        }
        // mobile手机号
        String mobile = (String) parameter.get("mobile");
        if(!StringUtils.isEmpty(mobile)){
            boolQuery.must(QueryBuilders.termQuery("destMobile",mobile));
        }
        // startTime开始时间,endTime结束时间
        Long startTime = (Long) parameter.get("startTime");
        Long endTime = (Long) parameter.get("endTime");
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if(startTime != null){
            rangeQuery.gte(startTime);
        }
        if(endTime != null){
            rangeQuery.lte(endTime);
        }
        boolQuery.must(rangeQuery);
        // 设置给sourceBuilder
        sourceBuilder.query(boolQuery);

        //3.2 设置分页信息
        Integer start = (Integer) parameter.get("start");
        Integer rows = (Integer) parameter.get("rows");
        sourceBuilder.from(start);    // TODO 是当前页, 还是起始索引
        sourceBuilder.size(rows);

        //3.3 设置高亮信息
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("messageContent");
        highlightBuilder.preTags((String) parameter.get("highLightPreTag"));
        highlightBuilder.postTags((String) parameter.get("highLightPostTag"));
        sourceBuilder.highlighter(highlightBuilder);

        request.source(sourceBuilder);

        //4. 执行查询并获取结果
        return restHighLevelClient.search(request, RequestOptions.DEFAULT);
    }
}
